<template>
  <div id="Add">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <!-- 提示信息区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
      </el-alert>
      <!-- 进度条区域 -->
      <el-steps :space="200" :active="activeIndex * 1" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <!-- Tab栏区域 -->
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="catelist"
                :props="cascaderProps"
                @change="parentCateChanged">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染动态参数 -->
            <el-form-item v-for="item in manyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(cb, i) in item.attr_vals" :key="i" :label="cb" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传 -->
            <!-- action图片上传的后台api地址 -->
            <!-- on-preview 图片预览事件 -->
            <!-- handleRemove图片删除事件 -->
            <!-- headers 配置上传请求头 -->
            <!-- on-success图片上传成功的钩子函数 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview" 
              :headers="headerObj" 
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce">
            </quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      
    </el-card>
    <!-- 图片预览 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewVisible"
      width="50%"
      >
      <img :src="previewPath" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
import { postHttpAddGoods  } from 'network/goodslist'
import { getHttpParentCateList  } from 'network/cate'
import { getHttpParamsData  } from 'network/params'
import { goodsnameVf, goodspriceVf, goodsweightVf, goodsnumberVf, goodscatVf } from 'common/js/validator'
//导入深拷贝插件
import _ from 'lodash'

export default {
  name: "Add",
  data() {
    return {
      //进度条步骤索引
      activeIndex: '0',
      //添加商品的数据对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      //添加商品验证对象
      addFormRules: {
        goods_name: goodsnameVf,
        goods_price: goodspriceVf,
        goods_weight: goodsweightVf,
        goods_number: goodsnumberVf,
        goods_cat: goodscatVf
      },
      //商品分类列表
      catelist: [],
      //级联菜单的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: false //是否运行选择一级分类
      },
      //动态参数列表数据
      manyTableData: [],
      //静态参数数据列表
      onlyTableData: [],
      //图片上传地址
      uploadURL: 'http://node.w-bf.com/api/private/v1/upload',
      //图片上传组件的请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //图片预览地址
      previewPath: '',
      //图片预览对话框显示及隐藏
      previewVisible: false
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取分类数据
    getCateList() {
      getHttpParentCateList(3).then(res => {
        if( res.meta.status !== 200) {         
          this.$message.error(res.meta.msg)
          return
        }
        else {
          this.catelist = res.data
        }
      }).catch(err => {
        this.$message.error(err)
      })
    },
    //级联选择器选中的值发生变化触发的事件
    parentCateChanged() {
      //证明选中的不是三级分类
      if(this.addForm.goods_cat.length !== 3) {
        this.$message.error('只允许选择3级分类')
        this.addForm.goods_cat = []
        return
      }
    },
    //标签页切换钩子函数
    beforeTabLeave(activeName, lodActiveName) {
      if(lodActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    //tab标签页被选中触发的函数
    tabClicked() {
      //表示访问的是商品参数页签
      if (this.activeIndex === '1') {
        getHttpParamsData(this.cateId,'many').then(res => {
          if( res.meta.status !== 200) {         
            this.$message.error(res.meta.msg)
            return
          }
          else {
            res.data.forEach(item => {
              //如果字符串为空就返回空数组，都在按空格分割数组
              item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
            })
            this.manyTableData = res.data
          }
        }).catch(err => {
          this.$message.error(err)
        })
      }
      else if (this.activeIndex === '2') {
        //访问的是静态属性面板
        getHttpParamsData(this.cateId,'only').then(res => {
          if( res.meta.status !== 200) {         
            this.$message.error(res.meta.msg)
            return
          }
          else {
            this.onlyTableData = res.data
          }
        }).catch(err => {
          this.$message.error(err)
        })
      }
    },
    //图片预览
    handlePreview(file) {
      console.log(file)
      this.previewPath = 'http://node.w-bf.com/' + file.response.data.tmp_path
      this.previewVisible = true
    },
    //图片删除事件
    handleRemove(file) {
      //获取将要删除图片的临时路径
      //const filePath = '/' + file.response.data.tmp_path
      const filePath =  file.response.data.tmp_path
      //从pics数组中找到这个图片对应的索引值
      const i = this.addForm.pics.findIndex(x => x.pic === filePath)
      //调用数组的splice方法，把图片信息从数组中移除
      this.addForm.pics.splice(i, 1)

    },
    //图片上传成功的钩子函数
    handleSuccess(response) {
      //tmp_path: "tmp_uploads/5dd45ba58206634983a1897d0861d3e7.jpg"
      if( response.meta.status !== 200) {         
        this.$message.error(response.meta.msg)
        return
      }
      else {
        //1、拼接得到一个图片信息对象
        //2、将图片信息对象 push到pics数组
        const picInfo = {
          //pic: '/' + response.data.tmp_path
          pic:  response.data.tmp_path
        }
        this.addForm.pics.push(picInfo)
        this.$message.success(response.meta.msg)
      }
    },
    //添加商品单击事件
    add() {
      this.$refs.addFormRef.validate(valid => {
        if(!valid) {
          this.$message.error('请填写必要的表单项')
          return
        }
        else {
          //深拷贝一个对象，如果用普通的赋值，是赋值的内存指针，深拷贝是完全拷贝一份新的
          const form = _.cloneDeep(this.addForm)
          form.goods_cat = form.goods_cat.join(',')
          //处理动态参数
          this.manyTableData.forEach(item => {
            const newInfo = {attr_id: item.attr_id , attr_value: item.attr_vals.join(' ')}
            this.addForm.attrs.push(newInfo)
          })
          //处理静态参数
          this.onlyTableData.forEach(item => {
            const newInfo = {attr_id: item.attr_id , attr_value: item.attr_vals}
            this.addForm.attrs.push(newInfo)
          })
          form.attrs = this.addForm.attrs
          postHttpAddGoods(form).then(res => {
            if( res.meta.status !== 201 ) {
              this.$message.error(res.meta.msg)
              return
            }
            else {
              this.$message.success(res.meta.msg)
              this.$router.push('/goods')
            }
          }).catch(err => {
            this.$message.error(err)
          })
        }
      })
    }
  },
  //计算属性
  computed: {
    //当前选中的三级分类的id
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      else {
        return null
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.btnAdd {
  margin-top: 15px;
}
</style>
